<template>
  <div class="manage">
    <el-dialog
      :title="dialogForm.type === 'add' ? '新增表' : '更新表'"
      :visible.sync="dialogForm.isShow"
      width="360px"
    >
      <CommonForm
        ref="myform"
        :formItemList="dialogForm.formItemList"
        :formData="dialogForm.formData"
        :inline="dialogForm.inline"
        :rules="dialogForm.rules"
      ></CommonForm>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm.isShow = false">取消</el-button>
        <el-button type="plain" @click="confirm">确定</el-button>
      </div>
    </el-dialog>


    <!-- 搜索 -->
    <div class="manage-header">
      <CommonForm
        :formItemList="searchForm.formItemList"
        :formData="searchForm.formData"
        :inline="searchForm.inline"
      >
        <el-button type="plain" @click="search" size="mini">搜索 <i class="el-icon-search"/></el-button>
        <el-button type="plain" class='reset' @click="reset" size="mini">重置 <i class="el-icon-refresh-left"/></el-button>
      </CommonForm>
    </div>

    <!-- 按钮区 -->
    <div style="margin-bottom: 5px">

      <el-button type="plain" @click="handleAdd" size="mini"
      >新增 <i class="el-icon-circle-plus-outline"></i>
      </el-button>
      <el-popconfirm
        style="margin-left: 10px"
        confirm-button-text='确定'
        cancel-button-text='我再想想'
        icon="el-icon-info"
        icon-color="red"
        title="你确定删除吗？"
        @confirm="handleDeleteBatch"
      >
        <el-button type="plain" size="mini" slot="reference"
        >批量删除 <i class="el-icon-remove-outline"></i>
        </el-button>
      </el-popconfirm>

    </div>

    <!--    数据表格-->
    <CommonTable
      :tableData="table.tableData"
      :tableLabel="table.tableLabel"
      :pageConfig="table.pageConfig"
      :defaultButtons="true"
    >
      <template v-slot:slot1="data">
        <el-button title="字段编辑" type="plain" @click="editColums(data)"><i class="el-icon-menu"/></el-button>
      </template>
    </CommonTable>
  </div>
</template>



<script>
import CommonForm from '../../../components/CommonForm'
import CommonTable from '../../../components/CommonTable'

import {
  add,
  getList,
  deleteOne,
  edit,
  deleteBatch
} from '../../../api/table'

import {findDataForSelect} from '../../../api/project'

export default {
  name: 'project',
  components: {
    CommonForm,
    CommonTable
  },
  data() {
    return {
      projectOptions: [],
      moduleText: '',
      dialogForm: {
        type: 'add', // add为新增，edit为编辑
        isShow: false,
        formItemList: [
          {
            name: 'pid',
            label: '所属项目',
            type: 'select',
            optionList: []
          },
          {
            name: 'tableName',
            label: '表名称',
            type: 'input',
          },
          {
            name: 'remark',
            label: '描述',
            type: 'input'
          },
          {
            name: 'packageName',
            label: '包名',
            type: 'input'
          }
        ],
        formData: {

        },
        inline: true,
        rules: {
          pid: [{required: true, message: '请输入所属项目', trigger: 'blur'}],
          tableName: [{required: true, message: '请输入表名称', trigger: 'blur'}],
          remark: [{required: true, message: '请输入描述', trigger: 'blur'}],
          packageName: [{required: true, message: '请输入包名', trigger: 'blur'}]
        }
      },
      searchForm: {
        formItemList: [
          {
            name: 'projectId',
            label: '所属项目',
            type: 'select',
            icon: 'el-icon-search',
            optionList: []
          }
          ,
          {
            name: 'tableName',
            label: '关键字',
            type: 'input',
            icon: 'el-icon-search'
          }
        ],
        formData: {
          tableName: ''
        },
        inline: true
      },

      table: {
        tableData: [],
        tableLabel: [
          {
            name: 'id',
            label: '表编号',
            type: 'column',
            width: 40
          },
          {
            name: 'tableName',
            label: '表名称',
            type: 'column'
          },
          {
            name: 'remark',
            label: '描述',
            type: 'column'
          },
          {
            name: 'packageName',
            label: '包名',
            type: 'column'
          },
          {
            name: 'pname',
            label: '所属项目',
            type: 'column'
          },
          {
            name: 'createUserName',
            label: '作者',
            type: 'column',
            width: 50
          }
        ],
        pageConfig: {
          total: 10, // 记录总数
          current: 1, // 起始页
          size: 10 // 每页展示的记录数
        }
      },
      ids: [],

    }
  },
  computed: {

  },
  methods: {


    /**
     * 编辑表字段
     * @param data
     */
    editColums(data){
      let tid = data.obj.id;
      this.$router.push({
        path: '/home',
        query: {
          tid
        }
      })

    },

    /**
     * 单个删除
     * @param id
     */
    handleDelete(id) {
      deleteOne(id).then(
        response => {
          if (response.code === 200) {
            this.$message.success("删除成功！")
            this.loading()
          } else {
            this.$message.error("删除失败！")
          }
        }
      )
    },
    /**
     * 批量删除
     */
    handleDeleteBatch() {
      if(!this.ids.length){
        this.$message.error("请至少勾选一个 表！")
        return
      }
      deleteBatch(this.ids).then(response => {
        if (response.code === 200) {
          this.$message.success("批量删除成功！")
          this.loading()
        } else {
          this.$message.error("批量删除失败！")
        }
      })
    },
    /**
     * 打开编辑页面
     * @param row
     */
    handleEdit(row) {
      this.dialogForm.isShow = true
      this.dialogForm.type = 'edit'
      console.log(row)
      this.dialogForm.formData = row
    },
    /**
     * 新增 或 修改
     */
    confirm() {
      this.$refs.myform.$refs.form.validate(valid => {  //表单提交时的验证

        if (valid) {
          // 通过type来判断是新增还是编辑
          if (this.dialogForm.type === 'add') {
            add(this.dialogForm.formData).then((response) => {
              if (response.code === 200) {
                this.$message.success("添加成功！")
                this.dialogForm.isShow = false
                this.loading()
              } else {
                this.$message.error("添加失败！")
              }
            })
          } else {
            edit(this.dialogForm.formData).then((response) => {
              if (response.code === 200) {
                this.$message.success("修改成功！")
                this.dialogForm.isShow = false
                this.loading()
              } else {
                this.$message.error("修改失败！")
              }
            })
          }
        }
      });


    },
    search() {
      this.loading()

    },
    // 重置搜索表单
    reset() {
      this.searchForm.formData = {}
      this.loading()
    },
    // 将数据渲染到表
    loading() {
      this.load();

      getList({
        current: this.table.pageConfig.current,
        size: this.table.pageConfig.size,
        tableName:this.searchForm.formData.tableName, //简单查询参数不要放在body里面
        projectId:this.searchForm.formData.projectId
      }).then(response => {
        if (response.code === 200) {
          this.table.tableData = response.data.list
          this.table.pageConfig.total = response.data.total
        } else {
          this.$message.error(response.message)
        }
      })
    },

    /**
     *     点击新增按钮，弹出对话框
     */
    handleAdd() {
      this.dialogForm.isShow = true
      this.dialogForm.type = 'add'
      this.dialogForm.formData = {}
    },

    loadProjects() {
      findDataForSelect().then(response => {
        console.log(response.data)
        response.data.forEach(obj => {
          // 只是作为演示，如果有字段不同，不劳烦后端处理了
         if (obj.hasOwnProperty('tableName')) {
            obj.name = obj.tableName;
            delete obj.tableName; // 删除原来的tableName属性（可选）
          }
        });
        this.projectOptions = response.data;
        this.searchForm.formItemList[0].optionList = this.projectOptions;
        this.dialogForm.formItemList[0].optionList = this.projectOptions;

      });
    }
  },
  created() {
    this.loading()
    //加载项目查询下拉
    this.loadProjects();
  },
  mounted() {
    this.$bus.$on("sizeChange", size => {
      this.table.pageConfig.size = size
      this.loading()
    })
    this.$bus.$on("currentChange", current => {
      this.table.pageConfig.current = current
      this.loading()
    })
    this.$bus.$on("del", row => {
      this.handleDelete(row.id)
    })
    this.$bus.$on("edit", row => {
      this.handleEdit(row)
    })
    this.$bus.$on("selectionChange", val => {
      this.ids = val.map(item => item.id) // [{},{},{}] => [1,2,3]
    })
  },
  beforeDestroy() {
    // 销毁事件
    this.$bus.$off("sizeChange")
    this.$bus.$off("currentChange")
    this.$bus.$off("del")
    this.$bus.$off("edit")
    this.$bus.$off("selectionChange")
  },

  filters: {

  }
}


</script>


<style lang="less" scoped>

.form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form__item {
  margin-bottom: 16px;
}

.form__label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
}

.form__input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 300px;
  font-size: 16px;
}

.form__submit {
  margin-top: 16px;
  padding: 8px 16px;
  background-color: #3f51b5;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
}

.form__submit:hover {
  background-color: #283593;
}

</style>
